package org.sundatagroup.aurora.show.controller;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.sundatagroup.aurora.core.controller.IJsonResultController;

import java.io.IOException;

/**
 * 后端向 display 发送消息的 websocket 控制器
 *
 * @author l_y_u
 * @date 2018-05-30
 * @since 0.2.0
 */
@Component
public class DisplaySocketController implements IJsonResultController {
	
	/**
	 * 接受指令并发送给前端
	 * @param session
	 * @param data
	 */
	public void pushCommand(WebSocketSession session, JsonObject data) {
		JsonObject res = new JsonObject();
		res.addProperty("type", "/show/message");
		res.addProperty("result",true);
		res.add("data", data);

		try {
			synchronized (session) {
				session.sendMessage(new TextMessage(res.toString()));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 成功查询
	 * @param session
	 * @param type
	 * @param data
	 */
	public void queryReturn(WebSocketSession session, String type, JsonElement data) {
		JsonObject jo = rawResultJsonObject(true);
		jo.addProperty("type", type);
		jo.add("data", data);

		try {
			synchronized (session) {
				session.sendMessage(new TextMessage(jo.toString()));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 失败查询
	 * @param session
	 * @param type
	 */
	public void queryReturnFall(WebSocketSession session, String type) {
		JsonObject jo = rawResultJsonObject(false);
		jo.addProperty("type", type);

		try {
			synchronized (session) {
				session.sendMessage(new TextMessage(jo.toString()));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
